$(function () {
    //加载弹出层
    layui.use(['form', 'element'],
        function () {
            layer = layui.layer;
            element = layui.element;
        });


    //触发事件
    var tab = {
        tabAdd: function (title, url, id) {
            //新增一个Tab项
            element.tabAdd('xbs_tab', {
                title: title
                ,
                content: '<iframe tab-id="' + id + '" frameborder="0" src="' + url + '" scrolling="yes" class="x-iframe"></iframe>'
                ,
                id: id
            })
        }
        , tabDelete: function (othis) {
            //删除指定Tab项
            element.tabDelete('xbs_tab', '44'); //删除：“商品管理”


            othis.addClass('layui-btn-disabled');
        }
        , tabChange: function (id) {
            //切换到指定Tab项
            element.tabChange('xbs_tab', id); //切换到：用户管理
        }
    };


    tableCheck = {
        init: function () {
            $(".layui-form-checkbox").click(function (event) {
                if ($(this).hasClass('layui-form-checked')) {
                    $(this).removeClass('layui-form-checked');
                    if ($(this).hasClass('header')) {
                        $(".layui-form-checkbox").removeClass('layui-form-checked');
                    }
                } else {
                    $(this).addClass('layui-form-checked');
                    if ($(this).hasClass('header')) {
                        $(".layui-form-checkbox").addClass('layui-form-checked');
                    }
                }

            });
        },
        getData: function () {
            var obj = $(".layui-form-checked").not('.header');
            var arr = [];
            obj.each(function (index, el) {
                arr.push(obj.eq(index).attr('data-id'));
            });
            return arr;
        }
    }

    //开启表格多选
    tableCheck.init();


    $('.container .left_open i').click(function (event) {
        if ($('.left-nav').css('left') == '0px') {
            $('.left-nav').animate({left: '-221px'}, 100);
            $('.page-content').animate({left: '0px'}, 100);
            $('.page-content-bg').hide();
        } else {
            $('.left-nav').animate({left: '0px'}, 100);
            $('.page-content').animate({left: '221px'}, 100);
            if ($(window).width() < 768) {
                $('.page-content-bg').show();
            }
        }

    });

    $('.page-content-bg').click(function (event) {
        $('.left-nav').animate({left: '-221px'}, 100);
        $('.page-content').animate({left: '0px'}, 100);
        $(this).hide();
    });

    $('.layui-tab-close').click(function (event) {
        $('.layui-tab-title li').eq(0).find('i').remove();
    });

    $("tbody.x-cate tr[fid!='0']").hide();
    // 栏目多级显示效果
    $('.x-show').click(function () {
        if ($(this).attr('status') == 'true') {
            $(this).html('&#xe625;');
            $(this).attr('status', 'false');
            cateId = $(this).parents('tr').attr('cate-id');
            $("tbody tr[fid=" + cateId + "]").show();
        } else {
            cateIds = [];
            $(this).html('&#xe623;');
            $(this).attr('status', 'true');
            cateId = $(this).parents('tr').attr('cate-id');
            getCateId(cateId);
            for (var i in cateIds) {
                $("tbody tr[cate-id=" + cateIds[i] + "]").hide().find('.x-show').html('&#xe623;').attr('status', 'true');
            }
        }
    })

    //左侧菜单效果
    // $('#content').bind("click",function(event){
    $('.left-nav #nav li').click(function (event) {

        if ($(this).children('.sub-menu').length) {
            if ($(this).hasClass('open')) {
                $(this).removeClass('open');
                $(this).find('.nav_right').html('&#xe697;');
                $(this).children('.sub-menu').stop().slideUp();
                $(this).siblings().children('.sub-menu').slideUp();
            } else {
                $(this).addClass('open');
                $(this).children('a').find('.nav_right').html('&#xe6a6;');
                $(this).children('.sub-menu').stop().slideDown();
                $(this).siblings().children('.sub-menu').stop().slideUp();
                $(this).siblings().find('.nav_right').html('&#xe697;');
                $(this).siblings().removeClass('open');
            }
        } else {

            var url = $(this).children('a').attr('_href');
            var title = $(this).find('cite').html();
            var index = $('.left-nav #nav li').index($(this));

            for (var i = 0; i < $('.x-iframe').length; i++) {
                if ($('.x-iframe').eq(i).attr('tab-id') == index + 1) {
                    tab.tabChange(index + 1);
                    event.stopPropagation();
                    return;
                }
            }
            ;

            tab.tabAdd(title, url, index + 1);
            tab.tabChange(index + 1);
        }

        event.stopPropagation();

    })


    $('.layui-nav dd').click(function (event) {

        var url = $(this).children('a').attr('_href');
        var title = $(this).children('a').html();
        var index = $(this).attr('tab-id')

        for (var i = 0; i < $('.x-iframe').length; i++) {
            if ($('.x-iframe').eq(i).attr('tab-id') == index) {
                tab.tabChange(index);
                event.stopPropagation();
                return;
            }
        }
        ;
        tab.tabAdd(title, url, index);
        tab.tabChange(index);

        event.stopPropagation();

    })

    $('#reload').on('click', function () {
        location.replace(location.href);
    })
})
var cateIds = [];

function getCateId(cateId) {

    $("tbody tr[fid=" + cateId + "]").each(function (index, el) {
        id = $(el).attr('cate-id');
        cateIds.push(id);
        getCateId(id);
    });
}

/*弹出层*/

/*
    参数解释：
    title   标题
    url     请求的url
    id      需要操作的数据id
    w       弹出层宽度（缺省调默认值）
    h       弹出层高度（缺省调默认值）
*/
function x_admin_show(title, url, w, h, btn = ['保存', '关闭']) {
    if (title == null || title == '') {
        title = false;
    }
    ;
    if (url == null || url == '') {
        url = "404.html";
    }
    ;
    if (w == null || w == '') {
        w = ($(window).width() * 0.9);
    }
    ;
    if (h == null || h == '') {
        h = ($(window).height() - 50);
    }
    ;
    layer.open({
        type: 2,
        area: [w + 'px', h + 'px'],
        fix: false, //不固定
        maxmin: true,
        shadeClose: true,
        shade: 0.4,
        title: [title, 'font-weight: 600;font-size:17px'],
        content: url,
        btn,
        yes: function () {
            let iframes = $('iframe')[0].contentWindow.document.body
            $(iframes).find('#submitData').trigger('click');
        }
        , btn2: function () {
            layer.closeAll();
        }
    });
}

/*关闭弹出框口*/
function x_admin_close() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function x_admin_father_reload() {
    parent.location.reload();
}

/* 
    elem:upload上传按钮dom元素
    multiple:是否多选
    tokenUrl:oss授权验证接口地址
    client:oss方法 参数
    uploadElem:点击上传按钮dom元素
    chooseCallback:选择图片后的回调
    beforeUploadCallback:上传前的操作
    uploadSuccessCallback:上传成功的操作
    uploadErrorCallback:上传失败的操作
*/
function uploadFile(params) {
    let {
        elem,
        uploadElem,
        chooseCallback,
        beforeUploadCallback,
        uploadSuccessCallback,
        uploadErrorCallback,
        multiple = false,
        ossUrl,
        ossType
    } = params
    let oss = ossUrl ?? '/admin/Uploads/uploadCredentials';
    var layerMask;
    layui.use(['layer', 'element', 'form', 'upload'], function () {
        var upload = layui.upload, client, files;
        var init = new Promise((resolve, reject) => {
            // 请求oss sts临时授权接口
            $.ajax({
                url: oss,
                type: "post",
                async: false,
                success: function (data) {
                    client = new OSS({
                        accessKeyId: data.data.accessKeyId,
                        accessKeySecret: data.data.accessKeySecret,
                        stsToken: data.data.securityToken,
                        bucket: data.data.bucket,
                        region: data.data.region
                    })
                    resolve()
                }
            });
        });
        init.then(() => {
            // 调用layui上传
            upload.render({
                elem,
                multiple,
                accept: 'file',
                auto: false,
                choose: function (obj) {
                    files = obj.pushFile();
                    chooseCallback ? chooseCallback() : '';//选择文件后的操作
                    if (!uploadElem) {//如果没有全部上传按钮，则直接调用上传接口
                        allUpload()
                    }
                },
            })
            // 如果有全部上传接口,调用上传接口
            if (uploadElem) {
                $(uploadElem).click(function () {
                    allUpload()
                })
            }
        });

        // 全部上传
        function allUpload() {
            let arrFiles = Object.values(files);
            let arrFilesIndex = Object.keys(files);
            layerMask = layer.load(1, {
                shade: [0.4, '#000']
            });
            for (let i in arrFiles) {
                uploadOssPut(arrFiles[i].name, arrFiles[i], arrFilesIndex[i]);
            }
        }

        // 上传文件到oss
        function uploadOssPut(name, file, fileIndex) {
            beforeUploadCallback ? beforeUploadCallback() : '';//上传前的操作
            console.log(ossType);
            if (ossType == 1) {
                client.multipartUpload(fileName(name), file).then(function (v) {
                    layer.close(layerMask)
                    if (v.res.status === 200) { //上传成功
                        uploadSuccessCallback ? uploadSuccessCallback(v, name) : '';//上传成功的操作
                        delete files[fileIndex];
                        return false;
                    } else {
                        uploadErrorCallback ? uploadErrorCallback() : '';//上传失败的操作
                    }
                })
            } else if (ossType == 2) {
                client.put(fileName(name), file).then(function (v) {
                    layer.close(layerMask)
                    if (v.res.status === 200) { //上传成功
                        uploadSuccessCallback ? uploadSuccessCallback(v, name) : '';//上传成功的操作
                        delete files[fileIndex];
                        return false;
                    } else {
                        uploadErrorCallback ? uploadErrorCallback() : '';//上传失败的操作
                    }
                })
            }
        }
    })
}

/*
    批量上传
    elem:upload上传按钮dom元素
    multiple:是否多选
    tokenUrl:oss授权验证接口地址
    client:oss方法 参数
    chooseCallback:选择图片后的回调
    beforeUploadCallback:上传前的操作
    uploadSuccessCallback:上传成功的操作
    uploadErrorCallback:上传失败的操作
*/
function batchUploadFile(params) {
    let {elem, chooseCallback, beforeUploadCallback, uploadSuccessCallback, uploadErrorCallback, ossUrl} = params
    let oss = ossUrl ?? '/admin/Uploads/uploadCredentials';
    var layerMask;
    layui.use(['layer', 'element', 'form', 'upload'], function () {
        var upload = layui.upload, client, files;
        var init = new Promise((resolve, reject) => {
            // 请求oss sts临时授权接口
            $.ajax({
                url: oss,
                type: "post",
                async: false,
                success: function (data) {
                    client = new OSS({
                        accessKeyId: data.data.accessKeyId,
                        accessKeySecret: data.data.accessKeySecret,
                        stsToken: data.data.securityToken,
                        bucket: data.data.bucket,
                        region: data.data.region
                    })
                    resolve()
                }
            });
        });
        init.then(() => {
            // 调用layui上传
            upload.render({
                elem,
                multiple: true,
                accept: 'file',
                auto: false,
                choose: function (obj) {
                    files = obj.pushFile();
                    chooseCallback ? chooseCallback() : '';//选择文件后的操作
                    allUpload()
                },
            })
        });

        // 全部上传
        function allUpload() {
            let arrFiles = Object.values(files);
            let arrFilesIndex = Object.keys(files);
            layerMask = layer.load(1, {
                shade: [0.4, '#000']
            });
            for (let i in arrFiles) {
                uploadOssPut(arrFiles[i].name, arrFiles[i], arrFilesIndex[i], arrFilesIndex);
            }
        }

        let arrIndex = 0

        // 上传文件到oss
        function uploadOssPut(name, file, fileIndex, arrFilesIndex) {
            beforeUploadCallback ? beforeUploadCallback() : '';//上传前的操作
            client.put(fileName(name), file).then(function (v) {
                if (v.res.status === 200) { //上传成功
                    arrIndex++
                    if (arrFilesIndex.length === arrIndex) {
                        uploadSuccessCallback ? uploadSuccessCallback(v, name, true) : '';//上传成功的操作
                        layer.close(layerMask)
                        arrIndex = 0
                    } else {
                        uploadSuccessCallback ? uploadSuccessCallback(v, name, false) : '';//上传成功的操作
                    }

                    delete files[fileIndex];
                    return false;
                } else {
                    uploadErrorCallback ? uploadErrorCallback() : '';//上传失败的操作
                }
            })
        }
    })
}

//文件上传路径+文件名
function fileName(name) {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    return `${year}-${month}-${day}/${hour}-${minute}-${second}-${name}`;
}

//时间格式化
function dayjsFormat(time, type = true) {
    let date = new Date(time * 1000);
    let year = date.getFullYear();
    let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    let alltime = type ? `${year}-${month}-${day} ${hour}:${minute}:${second}` : `${year}-${month}-${day}`
    return alltime;
}


function Ajax(url, param, type = 'post') {
    return new Promise((resolve, reject) => {
        $.ajax({
            type: type,
            url: url,
            dataType: "json",
            data: param,
            success: function (result) {
                if (result.code === 101) {
                    top.location.href = '/admin/login/index'
                    return
                } else if (result.code === 200) {
                    resolve(result);
                } else {
                    layer.msg(result.message);
                }
            },
            error: function (error) {
                reject(error);
            }
        });
    });
}

// 获取浏览器参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return r[2];
    return null;
}

layui.config({
    base: '/admin/xadmin/lib/layui/'
}).extend({
    selectN: 'selectN',
})
layui.config({
    base: '/admin/xadmin/lib/layui/'
}).extend({
    selectM: 'selectM',
})

// 单选
function selectN(params) {
    let {
        url,
        selected,
        tips,
        name,
        field_id,
        field_Name,
        extraData = [],
        elem,
        loading = false,
        search,
        disabled
    } = params

    layui.use(['selectN'], function () {
        $ = layui.jquery;
        var selectN = layui.selectN;
        var layerMaskSelectN;
        if (loading) {
            layerMaskSelectN = layer.load(1, {
                shade: [0.4, '#000']
            });
        }
        Ajax(url, {}, 'get').then(data => {
            layer.close(layerMaskSelectN)

            if (data.code === 200) {
                selectN({
                    //元素容器【必填】
                    elem

                    //候选数据【必填】
                    , data: extraData.concat(data.data)

                    //默认值
                    , selected

                    , tips

                    //input的name 不设置与选择器相同(去#.)
                    , name

                    //候选项数据的键名
                    , field: {idName: field_id, titleName: field_Name}
                    , search
                    , disabled
                });
            }
        });
    });
}

// 多选
function selectM(params) {
    let {url, elem, selected, tips, name, field_id, field_Name, max, extraData = []} = params

    layui.use(['selectM'], function () {
        $ = layui.jquery;
        var selectM = layui.selectM
        Ajax(url, {}, 'get').then(data => {
            if (data.code === 200) {
                selectM({
                    //元素容器【必填】
                    elem

                    //候选数据【必填】
                    , data: extraData.concat(data.data)

                    //默认值
                    , selected

                    , max

                    , tips

                    //input的name 不设置与选择器相同(去#.)
                    , name

                    //候选项数据的键名
                    , field: {idName: field_id, titleName: field_Name}

                });
            }
        });
    });
}

/* 
    提交form表单
    addUrl:添加表单url
    editUrl:编辑表单url
    detailUrl:获取表单数据url
*/
function form_ajax(params) {
    let {addUrl, editUrl, detailUrl} = params
    layui.use(["form", "layer"], function () {
        $ = layui.jquery;
        var form = layui.form,
            layer = layui.layer;
        let id = GetQueryString('id')
        let submitButton = $('#submitData'); // 获取提交按钮
        if (id) {
            // 获取表单详情 并赋值
            Ajax(detailUrl, {id}, 'get').then(result => {
                //formAjax 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                form.val("formAjax", result.data);
            });
        }
        form.on('submit(submitData)', function (data) {
            var formData = data.field;
            let url = id ? editUrl : addUrl
            // 禁用提交按钮
            submitButton.prop('disabled', true);
            Ajax(url, formData).then(data => {
                if (data.code === 200) {
                    layer.msg(data.message, {
                        icon: 6,
                        time: 1000
                    }, function () {
                        // 重新启用提交按钮
                        submitButton.prop('disabled', false);
                        //关闭当前frame
                        x_admin_close();
                        // 可以对父窗口进行刷新
                        id ? '' : x_admin_father_reload();

                    });
                }
            });
            return false
        });
    });
}

function form_ajaxon(params) {
    let {addUrl, editUrl, detailUrl} = params
    layui.use(["form", "layer"], function () {
        $ = layui.jquery;
        var form = layui.form,
            layer = layui.layer;
        let id = GetQueryString('id')
        if (id) {
            // 获取表单详情 并赋值
            Ajax(detailUrl, {id}, 'get').then(result => {
                //formAjax 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                form.val("formAjax", result.data);
            });
        }
        form.on('submit(submitData)', function (data) {
            var formData = data.field;
            let url = id ? editUrl : addUrl
            Ajax(url, formData).then(data => {
                if (data.code === 200) {
                    layer.msg(data.message, {
                        icon: 6,
                        time: 1000
                    }, function () {
                        //关闭当前frame
                        x_admin_close();
                        // 可以对父窗口进行刷新
                        x_admin_father_reload();

                    });
                }
            });
            return false
        });
    });
}

/* 
    tableList 表格列表
    elem:指定原始表格元素选择器（推荐id选择器）
    toolbar:开启表格头部工具栏区域
    url:数据接口
    id:表格id
    cols:表头
    page:分页
    limit:每页个数
*/
function tableList(params) {
    let {
        elem,
        toolbar,
        url,
        id,
        cols,
        page = true,
        limit = 10,
        where = {},
        height,
        width,
        totalRow,
        done,
        parseData = function (res) { //res 即为原始返回的数据
            return {
                "data": page ? res.data?.data ?? [] : res?.data ?? [], //解析数据列表
                "code": res.code, //解析接口状态
                'count': page ? res.data?.total ?? 0 : 0//解析数据长度
            };
        }
    } = params;
    layui.use(['table', "form", "layer"], function () {
        var table = layui.table
        form = layui.form,
            layer = layui.layer;
        //第一个实例
        table.render({
            elem
            , toolbar
            , url
            , id
            , cols
            , response: {
                statusCode: 200 //规定成功的状态码，默认：0
            }
            , limit
            , page
            , where
            , height
            , width
            , totalRow
            , done
            , parseData
        });
        form.on('submit(searchList)', function (data) {
            params.where = data.field
            tableList(params)
            return false
        });
        $('#resetList').on('click', function () {
            location.replace(location.href);
            // params.where = {}
            // tableList(params)
        });
    });
}

/* 
    tableAjax 表格删除
    url:数据接口
    params:参数
    fn:成功回调
*/
function tableAjax(url, params, id) {
    layui.use('table', function () {
        var table = layui.table;
        layer.confirm('确认要删除吗？', function () {
            Ajax(url, params).then(data => {
                if (data.code === 200) {
                    layer.msg(data.message, {
                        icon: 6,
                        time: 1000
                    }, function () {
                        table.reloadData(id)
                    });
                } else {
                    layer.alert(data.message);
                }
            })
        });
    });
}

/*
    tableChange 表格状态切换
    url:数据接口
    params:参数
    content:提示内容
    fn:成功回调
*/
function tableChange(url, params, id, content) {
    layui.use('table', function () {
        var table = layui.table;
        layer.confirm(content, function () {
            Ajax(url, params).then(data => {
                if (data.code === 200) {
                    layer.msg(data.message, {
                        icon: 6,
                        time: 1000
                    }, function () {
                        table.reloadData(id)
                    });
                } else {
                    layer.alert(data.message);
                }
            })
        });
    });
}

// 获取单选的值 infoSelectN
function getSelectNValue(option, value) {
    if ($.isFunction(window.infoSelectN)) {
        infoSelectN(option, value)
    }
    return {option, value}
}

/**
 * 展示图片
 * @param   {t} this   点击的this
 */
function showimg(t) {
    layer.open({
        type: 1,
        title: false,
        closeBtn: 1,
        skin: 'layui-layer-nobg', //没有背景色
        shadeClose: true,
        maxWidth: '400',
        content: '<img style="display: inline-block; width: 100%; height: 100%;" src="' + t.src + '">'
    });
}

/**
 * 计算百分比
 * @param   {number} num   分子
 * @param   {number} total 分母
 * @returns {number} 返回数百分比
 */
function Percentage(num, total) {
    if (num == 0 || total == 0) {
        return 0;
    }
    return (Math.round(num / total * 10000) / 100.00);// 小数点后两位百分比
}

/**
 * 计算人均值
 * @param   {number} num   分子
 * @param   {number} total 分母
 * @returns {number} 返回值
 */
function perCapita(num, total) {
    if (num == 0 || total == 0) {
        return 0;
    }
    return (num / total).toFixed(2);
} 